package cn.wisteria._properties.store;

import lombok.extern.slf4j.Slf4j;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;

/**
 * <p>
 * 写入properties文件类
 * </p>
 *
 * @author: zhu.chen
 * @date: 2020/12/28
 * @version: v1.0.0
 */
@Slf4j
public class PropertiesStoreHelper {

    /**
     * <p>
     * _properties#store存储properties文件
     * 会出现转义字符。
     * e.g：
     * password=admin== 写到文件里变成 password=admin\=\=
     * </p>
     *
     * @param filepath
     * @param properties
     */
    public static void store1(String filepath, Properties properties) {
        try (FileOutputStream fos = new FileOutputStream(filepath)) {
            properties.store(fos, null);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * <p>
     * 去除properties#store的转义字符。
     * </p>
     *
     * @param filepath
     * @param properties
     */
    public static void store2(String filepath, Properties properties) {
        try (FileOutputStream fos = new FileOutputStream(filepath)) {
            Enumeration<?> e = properties.propertyNames();
            while (e.hasMoreElements()) {
                String key = (String) e.nextElement();
                String value = properties.getProperty(key);
                String s = key + "=" + value + "\n";
                fos.write(s.getBytes());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


}
